package models

type Content struct {
	Model
	Title string `json:"title"`
	Tag string `json:"tag"`
	Content string `json:"content"`
	Top	int `json:"top"`
	CreateAt int64 `json:"create_at"`
	I18N string `json:"i18n"  gorm:"column:i18n"`
}

type Contents []Content

func (c Contents) Len() int {
	return len(c)
}

func (c Contents) Less(i, j int) bool {
	if c[i].Top > c[j].Top {
		return true
	} else {
		return c[i].CreateAt > c[j].CreateAt
	}
}

func (c Contents) Swap(i, j int) {
	c[i], c[j] = c[j], c[i]
}

func ExistContentByID(id int) bool {
	var content Content
	db.Select("id").Where("id = ?", id).First(&content)
	return content.ID > 0
}

func GetContents() (contents Contents) {
	db.Order("top DESC").Order("create_at DESC").Find(&contents)
	return
}

func GetContentsByOffset(limit []int) (total int, contents Contents) {
	db.Order("top DESC").Order("create_at DESC").Limit(limit[1]).Offset(limit[0]).Find(&contents)
	db.Model(&Content{}).Count(&total)
	return
}

func AddContent(titlie, tag, content, i18n string, top int, createAt int64) bool {
	db.Create(&Content{
		Title: titlie,
		Tag: tag,
		Content: content,
		I18N: i18n,
		Top: top,
		CreateAt: createAt,
	})
	return true
}

func DeleteContent(id int) bool {
	db.Where("id = ?", id).Delete(&Content{})
	return true
}

func UpdateContent(id int, data interface{}) bool {
	db.Model(&Content{}).Where("id = ?", id).Updates(data)
	return true
}